package com.xhtranslate.common.filter;

import com.xhtranslate.common.config.TranslateConfig;
import com.xhtranslate.common.util.JudgeCreditLimitUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author liuxuhuang
 * @version 1.0
 * @package com.xhtranslate.common.filter
 * @date 2022/11/20 23:22:08
 * @description 图片翻译判断是否超额
 */
@Slf4j
@Component
public class ImageTranslateFilter implements Filter {
    @Autowired
    private JudgeCreditLimitUtil judgeCreditLimitUtil;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info("图片翻译拦截");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String uri = request.getRequestURI();
        String sufferUrl = uri.substring(0, uri.lastIndexOf("/"));
        System.out.println(sufferUrl);
        System.out.println(ifBeyondCredit(sufferUrl));
        if (!ifBeyondCredit(sufferUrl)) {
            servletRequest.getRequestDispatcher("/overCreditReturn").forward(servletRequest, servletResponse);
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    /**
     * 是否超出额度 ,true未超出,false超出
     *
     * @param sufferUrl
     * @return boolean
     */
    public boolean ifBeyondCredit(String sufferUrl) {
        boolean flag = false;
        switch (sufferUrl) {
            case "/baiduTranslate":
                flag = judgeCreditLimitUtil.getBeyondOcrCredit(TranslateConfig.BaiduOcrRedisName, TranslateConfig.BaiduOcrRedisCreditLimit);
                break;
            case "/aliTranslate":
                flag = judgeCreditLimitUtil.getBeyondOcrCredit(TranslateConfig.AliOcrRedisName, TranslateConfig.AliOcrRedisCreditLimit);
                break;
            case "/youdaoTranslate":
                //flag = judgeCreditLimitUtil.getBeyondOcrCredit(TranslateConfig.YoudaoOcrRedisName, TranslateConfig.YoudaoOcrRedisCreditLimit);
                flag = false;
                break;
            default:
                flag = false;
                break;
        }
        return flag;
    }
}
